package com.project.lk.nurseapp.common.view.chat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseFragment;
import com.project.lk.nurseapp.common.view.chat.voice.AudioRecorderButton;
import com.project.lk.nurseapp.home.MainActivity;
import com.project.lk.nurseapp.utils.AddPhoto;
import com.project.lk.nurseapp.utils.ApkUtils;
import com.project.lk.nurseapp.utils.EditTextWatcher;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;
/**
 * 功能介绍：消息框
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class MessageInputToolBox extends LinearLayout {
	
	private OnOperationListener onOperationListener;

	private Map<Integer, ArrayList<String>> faceData=new HashMap<>();
	private List<Option> functionData;

	/** input box **/
	private EditText messageEditText;
	private Button faceButton;
	private Button sendButton;
	private Button moreTypeButton;

	/** face box **/
	private RelativeLayout bottomHideLayout;
	private  LinearLayout faceLayout;
	private ViewPager faceCategroyViewPager;
	private PagerSlidingTabStrip faceCategroyTabs;

	/** other function box **/
	private LinearLayout moreTypeLayout;
	private ViewPager fuctionViewPager;
	private LinearLayout pagePointLayout;
	List<View> functionGridViewList;
	List<ImageView> pointViews;

	private ListView mListView;

	private static boolean isShow=false;
	private Banner banner;
	//...

	FaceCategroyAdapter faceCategroyAdapter;

	private Context context;
	private FragmentManager fragmentManager;
	private GridView itemGridView;
	private LinearLayout messageItemLayout;
	private Button sendVoice;
	private SharedPreferences.Editor edit;
	private SharedPreferences preferences;
	private AudioRecorderButton audioButton;
	private LinearLayout viewPagerLayout;
	private LinearLayout messageInputLayout;

	String mSessionId="";
	public EditText getMessageEditText(){
		return this.messageEditText;
	}
	public MessageInputToolBox(Context context) {
		super(context);
		this.context = context;
		FragmentActivity fragmentActivity = (FragmentActivity) context;
		this.fragmentManager = fragmentActivity.getSupportFragmentManager();
		LayoutInflater.from(context).inflate(R.layout.message_input_tool_box, this);
	}

	public  void setSessionId(String sessionId){
		this.mSessionId=sessionId;
	}
	public MessageInputToolBox(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		FragmentActivity fragmentActivity = (FragmentActivity) context;
		this.fragmentManager = fragmentActivity.getSupportFragmentManager();
		LayoutInflater.from(context).inflate(R.layout.message_input_tool_box, this);


	}

	public MessageInputToolBox(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		FragmentActivity fragmentActivity = (FragmentActivity) context;
		this.fragmentManager = fragmentActivity.getSupportFragmentManager();
		LayoutInflater.from(context).inflate(R.layout.message_input_tool_box, this);
	}

Handler handler=	new Handler();
	public void scrollToBottom() {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				ListViewUtil.scrollToBottom(mListView);
				handler.removeCallbacks(this);
			}
		}, 200);
	}

	//设置获取listView的对象
	public void setListView(ListView view){

		mListView=view;
	}
	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		this.initView();
	}




	public boolean  getIsShow(){
		return isShow;
	}

	public  void setBanner(Banner banner){
		this.banner=banner;
	}
	private void initView(){

		preferences = context.getSharedPreferences("Height", MODE_PRIVATE);
		messageInputLayout = (LinearLayout) findViewById(R.id.message_input_layout);
		messageEditText 		= (EditText) findViewById(R.id.messageEditText);
			sendButton 				= (Button) findViewById(R.id.sendButton);
			sendVoice = (Button) findViewById(R.id.send_voice);
			bottomHideLayout		= (RelativeLayout) findViewById(R.id.bottomHideLayout);
		audioButton = (AudioRecorderButton) findViewById(R.id.recorder_button);
		faceButton	= (Button) findViewById(R.id.faceButton);
			moreTypeButton			= (Button) findViewById(R.id.moreTypeButton);
			moreTypeLayout			= (LinearLayout) findViewById(R.id.moreTypeLayout);
			messageItemLayout = (LinearLayout) findViewById(R.id.message_item_layout);
			faceLayout	= (LinearLayout) findViewById(R.id.faceLayout);
			faceCategroyViewPager 	= (ViewPager) findViewById(R.id.faceCategroyViewPager);
			//faceCategroyTabs 	= (PagerSlidingTabStrip) findViewById(R.id.faceCategroyTabs);
		//viewPagerLayout = (LinearLayout) findViewById(R.id.view_pager_layout);


		int height = preferences.getInt("height", 150);
		if (height>150){
			faceLayout.setMinimumHeight(height);
			messageItemLayout.setMinimumHeight(height);
			//为ViewPager设置高度
			ViewGroup.LayoutParams params = faceCategroyViewPager.getLayoutParams();
			params.height = height;
			faceCategroyViewPager.setLayoutParams(params);
			//int tabHeight = faceCategroyTabs.getHeight();
		}


		itemGridView = (GridView) findViewById(R.id.message_item_gridview);
		fuctionViewPager = (ViewPager) findViewById(R.id.fuctionViewPager);
		pagePointLayout = (LinearLayout) findViewById(R.id.pagePointLayout);

			fuctionViewPager.setOnPageChangeListener(new OnPageChangeListener() {

				@Override
				public void onPageSelected(int arg0) {
					for (int i = 0; i < pointViews.size(); i++) {
						if (arg0 == i) {
							pointViews.get(i).setBackgroundResource(R.drawable.point_selected);
						} else {
							pointViews.get(i).setBackgroundResource(R.drawable.point_normal);
						}
					}

				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {

				}

				@Override
				public void onPageScrollStateChanged(int arg0) {

				}
			});

			faceCategroyAdapter = new FaceCategroyAdapter(fragmentManager);
			faceCategroyAdapter.setViewPagerHeight(height);
			//发送消息
			sendButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(onOperationListener != null && !"".equals(messageEditText.getText().toString().trim())){
						String content = messageEditText.getText().toString();
						onOperationListener.send(content);
						messageEditText.setText("");
					}
				}
			});

			//点击表情按钮
			faceButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (banner!=null){
						banner.setVisibility(GONE);
					}
					scrollToBottom();
					if(faceLayout.getVisibility() == VISIBLE){
						hideFaceLayout();
						isShow=true;
						showKeyboard(context);
						faceButton.setBackgroundResource(R.drawable.biaoqing);
						audioButton.setVisibility(GONE);
					}else{
						showFaceLayout();
						faceButton.setBackgroundResource(R.drawable.jianpan);
					}


				}
			});

		//发送语音
		sendVoice.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!TextUtils.equals(mSessionId,"")) {
					scrollToBottom();
					if (audioButton.getVisibility()==GONE){
						audioButton.setVisibility(VISIBLE);
						//隐藏键盘和底下布局
						isShow=false;
						hideKeyboard(context);
						hide();
						sendVoice.setBackgroundResource(R.drawable.jianpan);
					}else {
						if (banner!=null){
							banner.setVisibility(GONE);
						}
						isShow=true;
						audioButton.setVisibility(GONE);
						sendVoice.setBackgroundResource(R.drawable.yuyin);
						showKeyboard(context);
						hide();
					}
				}else {

					ToastUtils.showShortToast("会话没有创建，请输入文字或选择表情创建会话");
				}


			}
		});
	//判断焦点是否改变
		messageEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus){
					hideFaceLayout();
					scrollToBottom();

				}else {
					//showKeyboard(context);
				}

			}
		});
			//点击消息输入框
			messageEditText.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (banner!=null){
						banner.setVisibility(GONE);
					}
					hideFaceLayout();
					isShow=true;
					messageEditText.setFocusable(true);
					//mListView.setSelection(mListView.getBottom());
					//下滚到最下面
					scrollToBottom();
					//showKeyboard(context);


				}
			});

			//消息框的文字变换监听
			messageEditText.addTextChangedListener(new EditTextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					if(s != null && !"".equals(s.toString().trim())){
						moreTypeButton.setVisibility(View.GONE);
						sendButton.setEnabled(true);
						sendButton.setVisibility(View.VISIBLE);
					}else{
						moreTypeButton.setVisibility(View.VISIBLE);
						if(moreTypeButton.getVisibility() == View.VISIBLE){
							sendButton.setVisibility(View.GONE);
						}
					}
				}
			});


			//点击+号按钮
			moreTypeButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
//					if (!TextUtils.equals(mSessionId,"")) {
//						hideKeyboard(context);
//						scrollToBottom();
//						moreTypeLayout.setVisibility(View.GONE);
//						faceLayout.setVisibility(View.GONE);
//						messageItemLayout.setVisibility(View.VISIBLE);
//						bottomHideLayout.setVisibility(View.VISIBLE);
//						if (banner!=null){
//							banner.setVisibility(GONE);
//						}
//					}else {
//						ToastUtils.showShortToast("会话没有创建，请输入文字或选择表情创建会话");
//					}

						hideKeyboard(context);
						scrollToBottom();
						moreTypeLayout.setVisibility(View.GONE);
						faceLayout.setVisibility(View.GONE);
						messageItemLayout.setVisibility(View.VISIBLE);
						bottomHideLayout.setVisibility(View.VISIBLE);
						if (banner!=null){
							banner.setVisibility(GONE);
						}

				}
			});
		setMessageItemAdapter();


		}

	//设置条目gridview的适配器
 	public void setMessageItemAdapter(){
		String[] str=new String[]{"拍照","相册","摄像"};
		int [] imageStr=new int[]{R.drawable.xiagji,R.drawable.zhaopian,R.drawable.shipin};
		List<Map<String,Object>> list=new ArrayList<>();

		for (int i=0;i<str.length;i++){
			Map<String,Object> map=new HashMap<>();
			map.put("image",imageStr[i]);
			map.put("str",str[i]);
			list.add(map);
		}
		SimpleAdapter adapter=new SimpleAdapter(context,list,R.layout.main_gridview_item,
				new String[]{"image","str"},new int[]{R.id.main_grid_view_icon,R.id.main_grid_view_title});
		itemGridView.setAdapter(adapter);


	}


	//设置发声音监听
	public void setVoiceItemEvent(AudioRecorderButton.AudioFinishRecorderCallBack callBack){
		audioButton.setFinishRecorderCallBack(callBack);
	}
	//设置项目点击事件
	public void setItemEvent(final BaseFragment fragment){

		itemGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (position){
					case 0: //拍照
						//Toast.makeText(PersonChatActivity.this,"...",Toast.LENGTH_LONG).show();
						if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId",""),"")){
							AddPhoto.takePicture((AppCompatActivity)context,fragment);
						}else {
							ToastUtils.showShortToast("会话没有创建，请发送一条文本消息创建会话");
						}


						break;
					case 1: //相册
						if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId",""),"")){
							List<String> mImageList=new ArrayList<String>();
							AddPhoto.openAlbum((AppCompatActivity)context,fragment,mImageList,4);
						}else {
							ToastUtils.showShortToast("会话没有创建，请发送一条文本消息创建会话");
						}

						break;
					case 2: //TODO:摄像

						break;
				}
			}
		});

	}
	public void setItemEvent(){

		itemGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (position){
					case 0: //拍照
						if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId",""),"")){
							if (ApkUtils.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
								//Toast.makeText(PersonChatActivity.this,"...",Toast.LENGTH_LONG).show();
								AddPhoto.takePicture((AppCompatActivity)context);
							}else {
								ToastUtils.showShortToast("你禁止了拍照权限，无法使用拍照功能");
							}
						}else {
							ToastUtils.showShortToast("会话没有创建，请发送一条文本消息创建会话");
						}

						break;
					case 1: //相册
						if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId",""),"")) {
							if (ApkUtils.hasPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
								List<String> mImageList=new ArrayList<String>();
								AddPhoto.openAlbum((AppCompatActivity)context,mImageList,4);
							}else {
								ToastUtils.showShortToast("你禁止了读取照片功能，无法使用相册");
							}
						}else {
							ToastUtils.showShortToast("会话没有创建，请发送一条文本消息创建会话");
						}


						break;
					case 2: //TODO:摄像 摄像

						if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId",""),"")){
							if (ApkUtils.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
									&&ApkUtils.hasPermission(Manifest.permission.RECORD_AUDIO)
									&&ApkUtils.hasPermission(Manifest.permission.CAMERA)) {
								AppCompatActivity activity = (AppCompatActivity) context;
								activity.startActivityForResult(new Intent(activity, CameraViewActivity.class), 100);
							}else {
								ToastUtils.showShortToast("你禁止了录像功能，无法使用摄像");
							}
						}else {
							ToastUtils.showShortToast("会话没有创建，请发送一条文本消息创建会话");
						}
						break;
				}
			}
		});

	}

	//显示表情布局
	public void showFaceLayout() {
		hideKeyboard(this.context);
		postDelayed(new Runnable() {
			@Override
			public void run() {
				bottomHideLayout.setVisibility(View.VISIBLE);
				faceLayout.setVisibility(View.VISIBLE);
				moreTypeLayout.setVisibility(View.GONE);
				messageItemLayout.setVisibility(View.GONE);
			}
		}, 50);
	}

	//隐藏表情界面
	public void hideFaceLayout(){
		moreTypeLayout.setVisibility(View.GONE);
		faceLayout.setVisibility(View.GONE);
		messageItemLayout.setVisibility(View.GONE);
		bottomHideLayout.setVisibility(View.GONE);
	}

	//隐藏
	public void hide(){
		moreTypeLayout.setVisibility(View.GONE);
		faceLayout.setVisibility(View.GONE);
		messageItemLayout.setVisibility(View.GONE);
		bottomHideLayout.setVisibility(View.GONE);
		hideKeyboard(context);

	}

	/**
	 * 隐藏软键盘
	 * @param
	 */
	public static void hideKeyboard(Context context) {
		Activity activity = (Activity) context;
		if(activity != null){
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			if(imm.isActive() && activity.getCurrentFocus() != null){
				imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
			}
		}
	}

	/**
	 * 显示软键盘
	 * @param
	 */
	public  void showKeyboard(Context context) {
		Activity activity = (Activity) context;
		if(activity != null){
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}



	public OnOperationListener getOnOperationListener() {
		return onOperationListener;
	}

	public void setOnOperationListener(OnOperationListener onOperationListener) {
		this.onOperationListener = onOperationListener;
		faceCategroyAdapter.setOnOperationListener(onOperationListener);
	}

	public Map<Integer, ArrayList<String>> getFaceData() {
		return faceData;
	}

	//设置表情数据
	public void setFaceData() {
//		this.faceData = faceData;
//	faceCategroyAdapter.setData(faceData);
		faceCategroyViewPager.setAdapter(faceCategroyAdapter);
		//faceCategroyTabs.setViewPager(faceCategroyViewPager);
//		if(faceData.size() < 2){
//			//faceCategroyTabs.setVisibility(GONE);
//		}
	}

	public List<Option> getFunctionData() {
		return functionData;
	}

	public void setFunctionData(List<Option> functionData) {
		this.functionData = functionData;
		pointViews = new ArrayList<ImageView>();
		functionGridViewList = new ArrayList<View>();

		for (int x = 0; x < (functionData.size() % 8 == 0 ? functionData.size() / 8 : (functionData.size() / 8) + 1); x++) {
			GridView view = new GridView(context);
			FunctionAdapter functionAdapter = new FunctionAdapter(context,
					functionData.subList(x * 8, 
							((x + 1) * 8) > functionData.size() ? functionData.size() : ((x + 1) * 8)));
			view.setAdapter(functionAdapter);
			//faceAdapters.add(emojiAdapter);

			view.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if (onOperationListener != null) {
						onOperationListener.selectedFuncation(position);
					}
				}
			});
			view.setNumColumns(4);

			view.setBackgroundColor(Color.TRANSPARENT);
			view.setHorizontalSpacing(1);
			view.setVerticalSpacing(1);
			view.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
			view.setCacheColorHint(0);
			view.setPadding(5, 0, 5, 0);
			view.setSelector(new ColorDrawable(Color.TRANSPARENT));
			view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT));
			view.setGravity(Gravity.CENTER);
			functionGridViewList.add(view);

			ImageView imageView = new ImageView(context);
			imageView.setBackgroundResource(R.drawable.point_normal);
			LayoutParams layoutParams = new LayoutParams(
					new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
			layoutParams.leftMargin = 10;
			layoutParams.rightMargin = 10;
			layoutParams.width = 8;
			layoutParams.height = 8;
			pagePointLayout.addView(imageView, layoutParams);
			if (x == 0) {
				imageView.setBackgroundResource(R.drawable.point_selected);
			}
			pointViews.add(imageView);
		}
//		PagerAdapter facePagerAdapter = new FacePagerAdapter(functionGridViewList);
		fuctionViewPager.setAdapter(new PagerAdapter() {
			@Override
			public int getCount() {
				return functionGridViewList.size();
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public int getItemPosition(Object object) {
				return super.getItemPosition(object);
			}

			@Override
			public void destroyItem(View arg0, int arg1, Object arg2) {
				System.out.println(arg0 + "  " + arg1 + "  " + arg2);
				((ViewPager) arg0).removeView(functionGridViewList.get(arg1));
			}

			/***
			 * 获取每一个item?类于listview中的getview
			 */
			@Override
			public Object instantiateItem(View arg0, int arg1) {
				((ViewPager) arg0).addView(functionGridViewList.get(arg1));
				return functionGridViewList.get(arg1);
			}
			
		});
		
	}

	
	
	
	
}
